package cn.kgc.util;

import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author wangyue
 * @version 1.0
 */
@ControllerAdvice("cn.kgc.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return  !returnType.getExecutable().isAnnotationPresent(IgnoreResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body == null){
            //如果控制器中原来的返回结果是null 直接返回一个包含null的Result对象
            return Result.success();
        }else if(body instanceof Result){
            //如果控制器的方法中原来的返回结果是result对象 直接将result对象返回
            return body;
        }else if(body instanceof String){
            //如果控制器的方法中原来的返回结果是String类型，则将String类型封装到Result对象中返回
            return JSONUtil.toJsonStr(Result.success(body));
        }else{
            //如果控制器的方法中原来的返回结果直接封装Result对象
            return Result.success(body);
        }
    }
}